package com.jinlejia.erp.ui.mine.contract;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfListRecyclerView;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.ListMapDropDownAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.BaseActivity;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityMyIntoBinding;
import com.jinlejia.erp.ui.mine.adapter.GirdDropDownAdapter;
import com.jinlejia.erp.ui.mine.adapter.MyIntoAdapter;
import com.jinlejia.erp.utils.DataFilter;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;


/**
 * 我的分成（activity）
 */

public class MyIntoActivity extends BaseActivity implements YfLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {



    private String headers[] = {"搜索", "合同类型", "分成缘由", "结佣状态"};
    private String type[] = {"不限", "买卖", "租赁", "一手房", "垫资", "金钥匙","法拍房"};
    //    private String cause[] = {"不限", "地址修正人", "电话添加人", "维护议价", "垫资清贷", "抵押代办",
//            "客源转介人", "协助签单", "成交责任人", "限时/独家委托", "钥匙责任人",
//            "客源合作成交人", "图片上传", "实勘图片修正", "其他"};
    private List<View> popupView = new ArrayList<>();

    private GirdDropDownAdapter typeAdapter;
    private ListMapDropDownAdapter reasonMenuAdapter;
    private ListMapDropDownAdapter commissionStateMenuAdapter;
    private MyIntoAdapter adapter;

    private ListView mTypeView;
    private ListView mCauseViews, commStateView;

    private YfListRecyclerView mRecyclerView;


    private EditText causeNumber;
    private EditText fenchengren;
    private TextView search;
    private TextView reset;


    private JSONObject jsonObject = new JSONObject();
    private int page = 1;
    private boolean mLoadingLock = false;
    private ArrayList<Map<String, Object>> dataList = new ArrayList<>();
    private InputMethodManager imm;
    ArrayList<Map<String, Object>> reasonList = new ArrayList<>();
    ArrayList<Map<String, Object>> commissionStateList = new ArrayList<>();

    private ActivityMyIntoBinding binding;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_my_into);
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        initView();
        initEvent();
    }

    @Override
    public void onStart() {
        super.onStart();
        page = 1;
        getData();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        binding.backBtn.setOnClickListener(view -> finish());
        binding.include.refreshLayout.setColorSchemeResources(R.color.yellow, R.color.light_yellow);
        binding.include.refreshLayout.setOnRefreshListener(this);
        //init contract menu
        final View contractFooter = this.getLayoutInflater().inflate(R.layout.myinto_search_footer, null);
        binding.include.dropDownMenu.setTabText(headers[0]);
        //合同编号输入框
        causeNumber = contractFooter.findViewById(R.id.search_edit);
        //分成人输入框
        fenchengren = contractFooter.findViewById(R.id.search_edit_man);
        //重置按钮
        reset = contractFooter.findViewById(R.id.reset);
        //搜索按钮
        search = contractFooter.findViewById(R.id.search);

        //init type menu
        mTypeView = new ListView(this);
        typeAdapter = new GirdDropDownAdapter(this, Arrays.asList(type));
        mTypeView.setAdapter(typeAdapter);


        //init time menu
        mCauseViews = new ListView(this);
        reasonMenuAdapter = new ListMapDropDownAdapter(this, reasonList);
        mCauseViews.setDivider(getResources().getDrawable(R.drawable.shape_h_line));
        mCauseViews.setAdapter(reasonMenuAdapter);

        // 结佣状态
        commStateView = new ListView(this);
        commissionStateMenuAdapter = new ListMapDropDownAdapter(this, commissionStateList);
        commStateView.setDivider(getResources().getDrawable(R.drawable.shape_h_line));
        commStateView.setAdapter(commissionStateMenuAdapter);

        //init popupViews
        popupView.add(contractFooter);
        popupView.add(mTypeView);
        popupView.add(mCauseViews);
        popupView.add(commStateView);

        TextView contentView = new TextView(this);
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
        contentView.setGravity(Gravity.CENTER);

        //init dropdownview
        binding.include.dropDownMenu.setDropDownMenu(Arrays.asList(headers), popupView, contentView);

        mRecyclerView = (YfListRecyclerView) findViewById(R.id.contract_recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.enableAutoLoadMore(this);

        adapter = new MyIntoAdapter(dataList);
        mRecyclerView.setAdapter(adapter);
        adapter.changeMode(YfListMode.MODE_LOADING);
    }

    /**
     * 初始化事件
     */
    private void initEvent() {

        mTypeView.setOnItemClickListener((adapterView, view, i, l) -> {
            typeAdapter.setCheckItem(i);
            binding.include.dropDownMenu.setTabText(i == 0 ? headers[1] : type[i]);
            if (i == 0) {
                jsonObject.remove("contractType");
            } else {
                jsonObject.put("contractType", i - 1);
            }
            getData();
            binding.include.dropDownMenu.closeMenu();
        });
        mCauseViews.setOnItemClickListener((adapterView, view, position, l) -> {
            reasonMenuAdapter.setCheckItem(position);
            binding.include.dropDownMenu.setTabText(position == 0 ? headers[2] : reasonList.get(position).get("valueName").toString());
            binding.include.dropDownMenu.closeMenu();
            if (reasonList.get(position).containsKey("valuel")) {
                jsonObject.put("reason", reasonList.get(position).get("valuel").toString());
            } else {
                jsonObject.put("reason", "");
            }
            page = 1;
            getData();
        });

        commStateView.setOnItemClickListener((parent, view, position, id) -> {
            commissionStateMenuAdapter.setCheckItem(position);
            binding.include.dropDownMenu.setTabText(position == 0 ? headers[3] : commissionStateList.get(position).get("valueName").toString());
            binding.include.dropDownMenu.closeMenu();
            if (commissionStateList.get(position).containsKey("valuel")) {
                jsonObject.put("commissionState", commissionStateList.get(position).get("valuel").toString());
            } else {
                jsonObject.put("commissionState", "");
            }
            page = 1;
            getData();
        });

        reset.setOnClickListener(view -> {
            binding.include.dropDownMenu.setTabText("搜索");
            fenchengren.setText("");
            causeNumber.setText("");
            jsonObject.remove("contractCode");
            jsonObject.remove("userName");
        });
        search.setOnClickListener(v -> {
            binding.include.dropDownMenu.setTabText("搜索");
            jsonObject.put("contractCode", causeNumber.getText().toString());
            jsonObject.put("userName", fenchengren.getText().toString());
            binding.include.dropDownMenu.closeMenu();
            getData();
            // 隐藏软键盘
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
        });

        adapter.OnIntoClickListener((state, Code) -> {
            if (state.equals("1")) {
                Intent intent = new Intent(MyIntoActivity.this, MyContractDetailsActivity.class);
                intent.putExtra("contractCode", Code);
                startActivity(intent);
            } else {
                CustomToast.showToast(MyIntoActivity.this, "成交人不是自己，无法查看", 2000);
            }
        });

    }


    /**
     * 获取数据
     */
    public void getData() {
        mLoadingLock = true;
        jsonObject.put("pageSize", 10);
        jsonObject.put("pageIndex", page);
        OkHttpUtils
                .postString()
                .url(ApiConfig.MY_INTO)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(MyIntoActivity.this, response, adapter)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            //修正缘由列表
                            reasonList = JSON.parseObject(data.getJSONArray("reasonList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            reasonMenuAdapter.setData(reasonList);
                            //结佣状态
                            commissionStateList = JSON.parseObject(data.getJSONArray("commissionStateList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            commissionStateMenuAdapter.setData(commissionStateList);
                            //数据列表
                            ArrayList<Map<String, Object>> list = JSON.parseObject(data.getJSONArray("page").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (page == 1) {
                                adapter.setData(list);
                            } else {
                                adapter.addData(list);
                            }
                        } else if (response.get("code").toString().equals("303")) {
                            //没有更多
                            if (page > 1)
                                page--;
                        } else if (response.get("code").toString().equals("501")) {
                            adapter.changeMode(YfListMode.MODE_EMPTY);
                        }
                        if (binding.include.refreshLayout.isRefreshing()) {
                            binding.include.refreshLayout.setRefreshing(false);
                        }
                        mLoadingLock = false;
                    }
                });
    }

    @Override
    public void loadMore() {
        if (adapter.getData().size() % 10 == 0) {
            if (mLoadingLock) {
                return;
            }
            mLoadingLock = true;
            page++;
            adapter.addFooter("loading");

            getData();
        } else if (adapter.getData().size() > 10) {
            adapter.addFooter(R.string.is_all);
        }
    }

    @Override
    public void onRefresh() {
        page = 1;
        getData();
    }
}
